package com.haois.mp.database.interceptor;

import com.haois.mp.database.commom.enums.ApiResultEnum;
import com.haois.mp.wechat.util.WxOAuth2AccessTokenUtil;

import com.haois.mp.database.commom.constant.StatusCode;
import com.haois.mp.database.exception.ErrorException;
import com.haois.mp.database.module.common.service.IUserTokenService;
import com.haois.mp.database.util.mp.HandleCookie;
import com.haois.mp.database.util.mp.HandleToken;
import org.apache.catalina.connector.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by RuiHaoZ on 2018/1/28 16:21
 */
@Component
public class SysInterceptor extends HandlerInterceptorAdapter {
    private static final Logger logger = LoggerFactory
            .getLogger(SysInterceptor.class);


    private IUserTokenService iUserTokenService;
    private WxOAuth2AccessTokenUtil wxOAuth2AccessTokenUtil;
    HandleToken handleToken = new HandleToken();

    public SysInterceptor(IUserTokenService iUserTokenService, WxOAuth2AccessTokenUtil wxOAuth2AccessTokenUtil) {
        this.iUserTokenService = iUserTokenService;
        this.wxOAuth2AccessTokenUtil = wxOAuth2AccessTokenUtil;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        try {
            String token = HandleCookie.getValueByName(request, StatusCode.COOKIE_JWT_WEB);
            String mid = handleToken.getValueByKey(token, StatusCode.SUBJECT_KEY_ID);
            String url = request.getRequestURI();
            logger.debug("管理员[{}]访问的路径为{}", mid, url);
            return true;
        } catch (NullPointerException e) {
            response.setStatus(Response.SC_UNAUTHORIZED);
            throw new ErrorException(ApiResultEnum.API_13.getCode(), "当前用户信息不存在，请重新登录");
        }
    }
}
